package com.d3works.apps.hr.service.expense;

import com.d3works.apps.base.db.Period;
import com.d3works.apps.base.db.repo.YearRepository;
import com.d3works.apps.base.service.app.AppBaseService;
import com.d3works.apps.hr.db.Expense;
import com.d3works.db.JPA;
import com.google.inject.Inject;

public class ExpenseFetchPeriodServiceImpl implements ExpenseFetchPeriodService {

  protected AppBaseService appBaseService;

  @Inject
  public ExpenseFetchPeriodServiceImpl(AppBaseService appBaseService) {
    this.appBaseService = appBaseService;
  }

  @Override
  public Period getPeriod(Expense expense) {

    return JPA.all(Period.class)
        .filter(
            "self.fromDate <= :todayDate AND self.toDate >= :todayDate "
                + "AND self.allowExpenseCreation = true "
                + "AND self.year.company = :company "
                + "AND self.year.typeSelect = :typeSelect")
        .bind("todayDate", appBaseService.getTodayDate(expense.getCompany()))
        .bind("company", expense.getCompany())
        .bind("typeSelect", YearRepository.TYPE_FISCAL)
        .fetchOne();
  }
}
